<!--
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-08 08:35:19
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-10-24 10:36:36
 * @FilePath: \keep_motion_manger\src\components\importDialog\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <el-dialog :title="title" width="500px" :model-value="visible" destroy-on-close :before-close="beforeClose">
        <el-form :inline="true" :model="editForm" class="editDialog-form" :rules="rules" ref="editFormRef">
            <template v-for="(item, index) in editItems.filter(item => item.type !== 'forbidden')" :key="index">
                <el-form-item :label="item.label" class="form-item" :prop="item.vModel">
                    <el-input v-if="item.type === 'input'" v-model="editForm[item.vModel]" :disabled="!canEdit || item.forbidden"><template #append v-if="item.unit">{{ item.unit }}</template> </el-input>
                    <el-switch v-else-if="item.type === 'switch'" v-model="editForm[item.vModel]" :disabled="!canEdit || item.forbidden" />
                    <el-input-tag v-else-if="item.type === 'tagInput'" v-model="editForm[item.vModel]" :max="5" clearable :disabled="!canEdit || item.forbidden"></el-input-tag>
                    <el-input-number v-else-if="item.type === 'Number'" v-model="editForm[item.vModel]" :min="item.min" :max="item.max" :step="item.step" step-strictly :disabled="!canEdit || item.forbidden" />
                    <el-select v-else-if="item.type === 'select'" v-model="editForm[item.vModel]" placeholder="请选择" clearable :disabled="!canEdit || item.forbidden" >
                        <el-option
                        v-for="option in item.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                        />
                    </el-select>
                    <el-date-picker
                        v-else-if="item.type === 'date'"
                        v-model="editForm[item.vModel]"
                        type="date"
                        placeholder="选择日期"
                        :disabled="!canEdit || item.forbidden" 
                    />
                    <el-upload
                        v-else-if="item.type === 'upload'"
                        class="avatar-uploader"
                        :action="`${baseUrl}${item.action(editItems[0].initialValue)}`"
                        :headers="uploadHeaders"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess.bind(this, item.vModel)"
                        :before-upload="beforeAvatarUpload.bind(this, item.fileType)"
                        :disabled="!canEdit || item.forbidden"
                    >   
                        <div class="avatar-uploader-container" v-if="editForm[item.vModel]">
                            <img v-if="!item.fileType" :src="`${baseUrl}${editForm[item.vModel]}`" class="avatar" />
                            <video v-else-if="item.fileType === 'video'" controls :src="`${baseUrl}${editForm[item.vModel]}`" class="avatar" />
                        </div>
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                    <el-button v-else-if="item.type === 'array'" type="primary" @click="handlePluralEdit(item.label, item.childItems, editForm[item.vModel])">{{title}}</el-button>
                </el-form-item>
            </template>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="beforeClose">取消</el-button>
                    <el-button type="primary" @click="handleSuccess" v-if="canEdit">确定</el-button>
                </span>
            </template>
    </el-dialog>
    <PluralEditDialog
        :title="pluralTitle"
        :visible="pluralDialogVisible"
        :editModule="pluralModule"
        :editData="pluralData"
        :dialogType="pluralDialogType"
        @successCallBack="handlePluralSuccess"
        @close="handlePluralClose"
    />
</template>

<script setup>

import { ref, reactive, onMounted, defineProps, defineEmits, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'

import PluralEditDialog from '@/components/pluralEditDialog/index.vue';

const baseUrl = import.meta.env.VITE_BASE_URL;
import { dictDataApi } from '@/api';
import './index.css';

const props = defineProps({
    visible: {
        type: Boolean,
        default: () => false
    },
    dialogType: {
        type: String,
        default: () => 'add'
    },
    editItems: {
        type: Array,
        default: () => []
    },
    rules: {
        type: Object,
        default: () => ({})
    }
});

const editFormRef = ref(null);

const emit = defineEmits(['close', 'successCallBack']);

const editForm = reactive({});


const pluralTitle = ref('');
const pluralDialogVisible = ref(false);
const pluralModule = ref([]);
const pluralData = ref([]);
const pluralDialogType = ref('add');

const canEdit = computed(() => {
    return props.dialogType !== 'view';
});
const title = computed(() => {
    return canEdit.value ? (props.dialogType === 'add' ? '新增' : '编辑') : '查看';
});
const uploadHeaders = computed(() => {
    return {
        Authorization: sessionStorage.getItem("role") + ' ' + sessionStorage.getItem('token'),
    }
})


// 模拟根据 code 获取下拉框选项
const getOptions = async (code) => {
  // 这里可以根据 code 调用接口获取对应选项
  const res = await dictDataApi.getDictData({code});
  if (res.code === 200) return res.data.rows;
  return [];
};
// 初始化表单数据
const initForm = () => {
    props.editItems.forEach(item => {
        editForm[item.vModel] = item.initialValue !== undefined ? item.initialValue : '';
    });
};
// 头像上传
const beforeAvatarUpload = (type = 'image', file) => {
    const allowHash = {
        image: ['image/jpeg', 'image/png', 'image/gif'],
        video: ['video/mp4', 'video/avi', 'video/mkv']
    }
    const tipsTextHash = {
        image: '图片',
        video: '视频'
    }
    const tipsTypeHash = {
        image: 'JPG, PNG, GIF',
        video: 'MP4, AVI, MKV'
    }
    const allowerList = allowHash[type];
    const isAllow = allowerList.includes(file.type);
    if (!isAllow) {
        ElMessage.error(`上传${tipsTextHash[type]}只能是 ${tipsTypeHash[type]} 格式!`);
    }
    return isAllow;
}
// 头像上传成功
const handleAvatarSuccess = (itemCode, res) => {
    editForm[itemCode] = res.data.file;
}

// plural
const handlePluralEdit = (title, childItems, data) => {
    pluralTitle.value = title;
    pluralModule.value = childItems;
    pluralData.value = data;
    pluralDialogVisible.value = true;
    pluralDialogType.value = props.dialogType;
}
const handlePluralSuccess = (key, data) => {
    editForm[key] = data;
    pluralDialogVisible.value = false;
}
const handlePluralClose = () => {
    pluralDialogVisible.value = false;
}

// 确定
const handleSuccess = async (res) => {
    const validate = await editFormRef.value.validate();
    if (!validate) return;
    emit('successCallBack', props.dialogType, editForm);
};

// 关闭前
const beforeClose = (done) => {
    emit('close');
};

onMounted(async () => {
  // 先获取所有下拉框的选项
  const optionPromises = props.editItems
    .filter(item => item.type === 'select')
    .map(async (item) => {
      const options = await getOptions(item.optionsCode);
      item.options = options;
    });

  await Promise.all(optionPromises);
});

watch(() => props.visible, (newVal) => {
    if (newVal) {
        initForm();
    }
})
</script>